#coding=utf-8
import mg_connection
import db
import mg_zone


#验证用户登陆信息
def vertifyUser(user,socket):
	#vertify user form DB,and coll the USER OBJECT
	#temp set the userid is 1,temp set the roomid is 1
	if db.vertifyUser(user):
		cache.cacheUser(user)
		mg_connection.vertifiedAddToSockets(user,socket)
		return True
	else:
		return False

#取得房间内用户信息TODO..分页存取
def getAllUsers():
	return cache.Users
	
#按房间id分离管理用户
def getAllUsersByRoomId():
	all = cache.Users
	rooms = []
	for user in all:
		try:
			index = rooms.index(all[user].getRoomId())
			rooms[index].append(all[user])
		except:
			rooms.append([all[user]])
	return rooms			

class cacheusers():

	def __init__(self):
		self.Users = {}

	def cacheUser(self,user):
		print "<-- MasterServer cache  a  user --> :",user.getId()
		self.Users[user.getId()] = user

	def updateUserRoom(self,userid,roomid,army):
		user = self.getUser(userid)
		user.setRoomId(roomid)
		user.setArmy(army)
	
	def updateUserHealth(self,userid,health):
		user = self.getUser(userid)
		user.setHealth(health)

	def getUser(self,userid):
		return self.Users[userid]

	def hasUser(self,user):
		return self.Users.has_key(user.getId())

#重置用户信息，清空roomid和health
	def resetUser(self,userid):
		self.getUser(userid).reset()	

#删除用户缓存
	def removeUser(self,userid):
		if self.Users[userid] is not None:
			user = self.Users[userid]
			#从房间内删除用户
			mg_zone.removeUserFromRoom(user)
			del self.Users[userid]
			del user
			print "<-- Cache remove user-->",userid


cache = cacheusers()		
